package com.stack.knowyoubase.config;

import com.stack.knowyoubase.anotional.TimeOut;
import com.stack.knowyoubean.bean.User;
import com.stack.knowyoudao.dao.UserDao;
import org.springframework.context.annotation.Scope;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 登录服务
 * @author stack
 */
@Service
@Scope("singleton")
public class LoginConfigImpl implements UserDetailsService {

    @Resource
    private UserDao userDao;

    /**
     * 用户登录 security
     *
     * @param username 用户名
     * @return userDetails 用户信息 security
     * @throws UsernameNotFoundException 用户名不存在
     */
    @Transactional(readOnly = true,rollbackFor = Throwable.class)
    @TimeOut
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if (StringUtils.isEmpty(username)) {
            throw new UsernameNotFoundException("用户名或密码错误");
        }
        User user = userDao.findUserByEmail(username);
        if (user == null) {
            int userId = 0;
            try {
                userId = Integer.parseInt(username);
            } catch (Exception e) {
                throw new UsernameNotFoundException("用户名或密码错误");
            }
            user = userDao.findUserById(userId);
            if (user == null) {
                throw new UsernameNotFoundException("用户名或密码错误");
            }
        }
        List<SimpleGrantedAuthority> authorityList = new ArrayList<>();
        String role = user.getRole();
        authorityList.add(new SimpleGrantedAuthority(role));
        return new org.springframework.security.core.userdetails.User(String.valueOf(user.getUserid()), user.getPassword(), authorityList);

    }
}
